package com.lalameow.loginbylogingate.util;

import com.lalameow.loginbylogingate.LoginByLoginGate;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;

/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2018/5/15
 * 时间: 15:45
 * 功能：请进行修改
 */
public class CryptUtil {


    public static KeyPair generateKeyPair()
    {
        try
        {
            KeyPairGenerator keypairgenerator = KeyPairGenerator.getInstance("RSA");
            keypairgenerator.initialize(1024);
            return keypairgenerator.generateKeyPair();
        }
        catch (NoSuchAlgorithmException nosuchalgorithmexception)
        {
            nosuchalgorithmexception.printStackTrace();
            return null;
        }
    }

    public static byte[] encryptData(Key key, byte[] data)
    {
        return cipherOperation(1, key, data);
    }

    /**
     * Decrypt byte[] data with RSA private key
     */
    public static byte[] decryptData(Key key, byte[] data)
    {
        return cipherOperation(2, key, data);
    }





    private static byte[] cipherOperation(int opMode, Key key, byte[] data)
    {
        try
        {
            return createTheCipherInstance(opMode, key.getAlgorithm(), key).doFinal(data);
        }
        catch (IllegalBlockSizeException | BadPaddingException e)
        {
            e.printStackTrace();
        }

        LoginByLoginGate.plugin.getLogger().info("Cipher data failed!");
        return null;
    }

    /**
     *
     * @param opMode Cipher.ENCRYPT_MODE加密 Cipher.DECRYPT_MODE解密
     * @param transformation
     * @param key
     * @return
     */
    private static Cipher createTheCipherInstance(int opMode, String transformation, Key key)
    {
        try
        {
            Cipher cipher = Cipher.getInstance(transformation);
            cipher.init(opMode, key);
            return cipher;
        }
        catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e)
        {
            e.printStackTrace();
        }

        LoginByLoginGate.plugin.getLogger().info("Cipher creation failed!");
        return null;
    }


}
